package cn.dceast.common.api;

import cn.dceast.common.data.RtnData;
import cn.dceast.common.utils.DataUtil;
import cn.dceast.common.utils.StringUtil;
import cn.dceast.former.service.EyeModelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/ResultDataApi.do")
@Api(tags = {"ResultDataApi.do"})
public class ResultDataApi {

    public static final Logger logger = LoggerFactory.getLogger(ResultDataApi.class);
    @Autowired
    private EyeModelService eyeModelService;
    /**
     * 根据API获取到结果数据
     * @param token token标识值(验证 )
     * @param resTableName 生成结果的表名称
     * @param request
     * @return
     */
    @ApiOperation(value = "根据API接口地址获取数据", notes = "根据API接口地址获取数据")
    @RequestMapping(value = "/getDataByApi", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getDataByApi(@RequestParam(required = true) String token,

                                @RequestParam(required = true) String resTableName,
                                HttpServletRequest request){
        if(StringUtil.isEmpty(token)){
            RtnData.fail("error","token值为空");
        }
        if(StringUtil.isEmpty(resTableName)){
            RtnData.fail("error","resTabelName值为空");
        }
        int result = eyeModelService.checkTokenState(token);
        if(result<1){
            RtnData.fail("error","token验证失败，请验证token值是否正确！");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("token",token);
        String pageSize = request.getParameter("pageSize")!=null?request.getParameter("pageSize").toString():null;
        String pageIndex = request.getParameter("pageIndex")!=null?request.getParameter("pageIndex").toString():null;
        paramMap.put("startIndex",pageIndex==null?"":Integer.parseInt(pageIndex)*Integer.parseInt(pageSize));
        paramMap.put("pageSize",pageSize==null?"":Integer.parseInt(pageSize));
        paramMap.put("resTableName",resTableName);
        List<Map<String,Object>> objList = eyeModelService.getResDataByApi(paramMap);
        if(DataUtil.isListNull(objList)){
            return RtnData.fail("error","没有结果数据返回");
        }
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put("result",objList);
        return RtnData.ok(returnMap);
    }
}
